package com.my.socket.nio.v21;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector acceptSelector;
    private Selector[] readWriteSelectors;
    private ServerSocketChannel serverSocketChannel;

    public Server(String host, int port) throws Exception {
        this.acceptSelector = Selector.open();
        this.readWriteSelectors = new Selector[1];
        for (int i = 0; i < this.readWriteSelectors.length; i++) {
            this.readWriteSelectors[i] = Selector.open();
        }
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
    }

    public void startup() throws Exception {
        new Thread(new AcceptTask(this.acceptSelector, this.readWriteSelectors), "accept-task").start();

        for (int i = 0; i < readWriteSelectors.length; i++) {
            Selector readWriteSelector = readWriteSelectors[i];
            new Thread(new ReadWriteTask(readWriteSelector), "read-write-task-" + i).start();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 9999;
        Server server = new Server(host, port);
        server.startup();
        LOGGER.info("listen at {}:{}", host, port);
    }
}
